package com.zhj.test.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @author zhj
 */
public class NIOClient {
    public static void main(String[] args) throws Exception {
        // 1.得到一个网络通道
        SocketChannel socketChannel = SocketChannel.open();
        // 2.设置非阻塞
        socketChannel.configureBlocking(false);
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666);
        // 3.连接服务器
        if (!socketChannel.connect(inetSocketAddress)) {
            while (!socketChannel.finishConnect()) {
                System.out.println("客户端因为连接需要时间，客户端不会阻塞");
            }
        }
        System.out.println("客户端连接服务器连接成功！");
        // 4.设置发送内容
        String str = "hello world!!!";
        // 5.将数据放入缓冲区 wrap可以根据字节数组大小分配大小
        ByteBuffer buffer = ByteBuffer.wrap(str.getBytes());
        socketChannel.write(buffer);
        System.in.read();
    }
}
